package twelve_config

/**
 * @Description 对任务配置模块请求的封装
 * @Author 007lz
 * @Date 2024/7/9 下午5:28
 **/
import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"time"

	"gitee.com/git-lz/twelve/common/consts"
	"gitee.com/git-lz/twelve/common/dto/response"
	"gitee.com/git-lz/twelve/common/httpclient"
	"gitee.com/git-lz/twelve/common/mjson"
	"gitee.com/git-lz/twelve/common/zaplog"
	"gitee.com/git-lz/twelve/model/task"
	"go.uber.org/zap"
)

// GetAllTasks
// Description 获取所有可用的任务
// return 任务配置，error
func (a *ApiInfo) GetAllTasks(ctx context.Context) ([]task.Task, error) {
	start := time.Now()

	client, err := httpclient.GetClient(ctx, a.Name)
	if err != nil {
		zaplog.Errorf(ctx, consts.DLTagGetHttpClientFailed, start, zap.Error(err))
		return nil, err
	}

	cResp := client.Get(ctx, fmt.Sprintf("%v%v", a.Host, a.GetAllTasksUrl))
	if cResp.Error() != nil || cResp.StatusCode() != http.StatusOK {
		zaplog.Errorf(ctx, consts.DLTagHttpFailed, start, zap.Error(err), zap.Any("resp", string(cResp.Content())))
		return nil, errors.New(fmt.Sprintf("err=(%v), code=(%v), content=(%v)",
			cResp.Error(),
			cResp.StatusCode(),
			string(cResp.Content())))
	}

	var resp response.Response
	if err := mjson.JsonIter.Unmarshal(cResp.Content(), &resp); err != nil {
		zaplog.Errorf(ctx, consts.DLTagJsonUnmarshalFailed, start, zap.Error(err))
		return nil, err
	}

	if !resp.IsSucc {
		err := errors.New(resp.Msg)
		zaplog.Errorf(ctx, consts.DLTagHttpFailed, start, zap.Error(err))
		return nil, err
	}

	var tasks []task.Task
	if err := mjson.UnmarshalFromInterface(resp.Data, &tasks); err != nil {
		zaplog.Errorf(ctx, consts.DLTagJsonUnmarshalFailed, start, zap.Error(err))
		return nil, err
	}

	zaplog.Info(ctx, consts.DLTagSuccess, start, zap.Any("tasks", tasks))
	return tasks, nil
}
